import base64
import datetime
import json
import time
import traceback
import urllib
import uuid
import requests
import hashlib
import urllib.parse
import des

base_url = 'https://shennong.proxyyouneed.top/'
apikey = '536cac01969bc124565d26a3d9cce5e2'

def get_nonce():
    return str(uuid.uuid4())


def create_signature(value, current_datetime, nonce):
    return hashlib.md5((apikey + value + current_datetime + nonce).encode('utf-8')).hexdigest()

def get_current_datetime():
    # 获取当前日期时间
    current_datetime = datetime.datetime.now()
    formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_datetime


def create_params(data):
    current_datetime = get_current_datetime()
    value = urllib.parse.urlencode(data)
    nonce= get_nonce()
    signature = create_signature(value, current_datetime, nonce)
    params = {
        'd': base64.b64encode(des.aes_encrypt(value).encode('utf-8')),
        't': current_datetime,
        's': signature,
        'n': nonce
    }
    return urllib.parse.urlencode(params)


def create_content(response):
    content = response.content.decode('utf-8')
    content = des.aes_decrypt(content)
    content = json.loads(content)
    if int(content['c']) != 1:
        return False, content['m']
    # 如果这个加密串时间过期，则不能再次使用了
    if (int(time.time()) - int(content['t'])) > 5:
        return False, None
    return True, content.get('d', None)


def user_check(data):
    try:
        response = requests.get(f'{base_url}app/user/check?' + create_params(data), timeout=5)
        return create_content(response)
    except Exception as e:
        traceback.print_exc()
        return False, e


def user_transfer(message):
    try:
        headers = {
            'Connection': 'keep-alive',
            'Content-Type': 'application/json; charset=utf-8'
        }
        preload = {
            "messages": [
                {
                    "role": "user",
                    "content": message
                }
            ]
        }
        response = requests.post(f'{base_url}app/gpt/transfer/send', json={
            'package': des.aes_encrypt(json.dumps(preload))
        }, timeout=10, headers=headers)
        return True, json.loads(response.text)['output']['text']
    except Exception as e:
        traceback.print_exc()
        return False, e


def user_tips(message, gpt_tips=''):
    try:
        headers = {
            'Connection': 'keep-alive',
            'Content-Type': 'application/json; charset=utf-8'
        }
        preload = {
            "gpt_tips": gpt_tips,
            "messages": [
                {
                    "role": "user",
                    "content": message
                }
            ]
        }
        response = requests.post(f'{base_url}app/gpt/tips/send', json={
            'package': des.aes_encrypt(json.dumps(preload))
        }, timeout=10, headers=headers)
        return True, json.loads(response.text)['output']['text']
    except Exception as e:
        traceback.print_exc()
        return False, e


def user_infer(message, style=''):
    try:
        headers = {
            'Connection': 'keep-alive',
            'Content-Type': 'application/json; charset=utf-8'
        }
        preload = {
            "style": style,
            "messages": [
                {
                    "role": "user",
                    "content": message
                }
            ]
        }
        response = requests.post(f'{base_url}app/gpt/infer/send', json={
            'package': des.aes_encrypt(json.dumps(preload))
        }, timeout=10, headers=headers)
        return True, json.loads(response.text)['output']['text']
    except Exception as e:
        traceback.print_exc()
        return False, e


# if __name__ == '__main__':
#     status, package = user_check({
#         'did': '123'
#     })
#     print(status, package)
#
#     status, package = user_transfer("你好啊")
#     print(status, package)
#
#     status, package = user_tips("“刚满十八岁～”#蜡笔小新野原新之助小新的骚操作为什么我不笑，因为我真的刚满十八岁“刚满十八岁～”放到小新身上反而感觉挺合理的这个声音终于找到完美的宿主了第一次没觉得这个声音恶心对小新来说就是正常操作小新：", "#情感 #风趣 #文艺 #日常 #影视 #音乐 #旅行 #美食 #家居 #办公 #科技 #美女 #动漫 #动画")
#     print(status, package)
#
#     status, package = user_infer("“刚满十八岁～”#蜡笔小新野原新之助小新的骚操作为什么我不笑，因为我真的刚满十八岁“刚满十八岁～”放到小新身上反而感觉挺合理的这个声音终于找到完美的宿主了第一次没觉得这个声音恶心对小新来说就是正常操作小新：我不要男孩子 我要大姐姐小新好像真没有喜欢过十八岁以下的女生这是看小新最无语的一次哎呦~ 讨厌~超爱这张没看过蜡笔小新 来个人 动画片真这样吗很适合蜡笔小新贱萌贱萌的让我的朋友也看看是这个嘛 刚满十八岁哈哈哈哈哈哈哈哈哈哈", '正能量、正义、严肃')
#     print(status, package)




